﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace Validation
{
    public partial class TextboxWithValidationOptions : System.Web.UI.UserControl
    {
        public enum ValidationType {None, Name, Integer, Decimal, Username }

        public ValidationType Type { get; set; }
        public string CssClass { get; set; }
        public string LabelText { get; set; }
        public bool Required { get; set; }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.CssClass != null)
            {
                uiTextbox.CssClass = CssClass;
            }
            if (LabelText != null)
                uiLabel.Text = LabelText;

            if (Required == true)
            {
                RequiredFieldValidator rValidator = new RequiredFieldValidator();
                rValidator.ControlToValidate = uiTextbox.ID;
                rValidator.ErrorMessage = "Dette felt må ikke være tomt";
                rValidator.Text = "*";
                this.Controls.Add(rValidator);
            }

            if (Type != ValidationType.None)
            {
                string regExp = "";
                string msg = "";

                switch(Type)
                {
                    case ValidationType.Decimal:
                            regExp = @"[0-9]+(\,[0-9]+)?";
                            msg = "Dette felt kræver et decimalt tal";
                            break;
                    case ValidationType.Integer:
                            regExp = @"[+-]?^\d+$";
                            msg = "Dette felt kræver et hel-tal";
                            break;
                    case ValidationType.Name:
                            regExp = @"[a-zA-Z]+";
                            msg = "Dette felt accepterer kun bogstaver";
                            break;
                    case ValidationType.Username:
                            regExp = @"[a-zA-Z][a-zA-Z0-9]+";
                            msg = "Dette felt kræver bogstaver, eventuelt efterfulgt af tal";
                            break;
                }

                RegularExpressionValidator expValidator = new RegularExpressionValidator();
                expValidator.ID = "uiRegExpValidator";
                expValidator.ControlToValidate = uiTextbox.ID;
                expValidator.ValidationExpression = regExp;
                expValidator.ErrorMessage = msg;
                expValidator.Text = "*";
                this.Controls.Add(expValidator);
            }
        }
    }
}